#!/usr/bin/ruby

# file:     yamltunesmail.rb
# author:   davidfmiller http://www.fivevoltlogic.com/code/mytunes/
# version:  v0.1.2
# about:    a script that reads in email messages stored on disk saved via
#           Apple's Mail.app and parses the message content to add any
#           attached files to iTunes and tracks to given playlists in your
#           music library (specified through YAML); see the included
#           readme for more information)
#
# history:  v0.1 thurs june 30, 2005
#            - initial version complete
#
#           v0.1.1 wed july 6, 2005
#            - added ability to create new a playlist if a playlist specified
#               in yaml doesn't exist
#            - check iTunes version to prevent tracks from being added to the
#               podcasts playlist
#            - changed accepted yaml format to something a little more concise
#     
#           v0.1.2 tue july 12, 2005
#            - added growl support
#            - changed script to read email message from email file on disk
#               rather than communicating with Mail.app through AppleScript
#               (for performance reasons)

#           v0.1.3 fri jul 29, 2005
#            - now looks for document terminator ('...') to separate the
#               message body from the plist stuff at the bottom of the emlx
#               file


# ---
# "d.new":
#  - buck 65 : blood of a young wolf
#  - jason collett : hangover days
# 
# porno:
#  - a.c. newman : the town halo
#  - the new pornographers : twin cinema
# ...


require 'rmail'
require 'base64'
require 'yamltunes'

def getYAMLFromMessage(body) 

	yaml = ''
	flag = false

	# find first occurrence of "---" and start from there
	body.each_line { |line|

		if (flag && yaml.length && (line =~ /^[^-]+$/)) 
			yaml = yaml.strip + " " + line
		else
			yaml += line if flag 
		end

		flag = true if line =~ /^---\s*$/ # if the start has been found, then set a flag to start slurping the input
		break if line =~ /^\.\.\.\s*$/ # found the end
		
		# check to see if this line has been wrapped by mail (boo)
	}

	yaml + "\n" 
end


if (ARGV.length == 0) 
	puts " usage: " + $0 + " [path to .emlx file] ..."
	exit
end


ARGV.each { |a|
	File.open(a, 'r') { |f|

		message = RMail::Parser.read(f)
		i = 0
		body = '';

		# does this message contain any attachments?
		if (! message.multipart?) 
			body = message.to_s
		else
			message.each_part { |part|
				i = i + 1
				body = part.to_s if i == 1
			}
		end

		yaml = getYAMLFromMessage(body)
		yamltunes = YAMLTunes.new(yaml)
		yamltunes.run
	}
}
